package com.zsy;

import com.alibaba.fastjson.JSONObject;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.*;

public class Xml2Json {
    /**
     * 转换一个xml格式的字符串到json格式
     *
     * @param xml xml格式的字符串
     * @return 成功返回json 格式的字符串;失败反回null
     */
    @SuppressWarnings("unchecked")
    public static String xml2JSON(String xml) {
        JSONObject obj = new JSONObject();
        try {
            Document doc = DocumentHelper.parseText(xml);
            Element root = doc.getRootElement();

            return obj.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 迭代解析xml方法
     *
     * @param element
     * @return java.util.Map 实例
     */
    @SuppressWarnings("unchecked")
    public static Map iterateElement(Element element) {
        Map obj = new HashMap();
        List<Element> list = element.elements();
        if (list.size() == 0) {
            obj.put("value", element.getText());
            Iterator iterator = element.attributeIterator();
            while (iterator.hasNext()) {
                Attribute attr = (Attribute) iterator.next();
                obj.put(attr.getName(), attr.getValue());
            }
        } else if (list.size() == 1) {
            Iterator iterator = element.attributeIterator();
            while (iterator.hasNext()) {
                Attribute attr = (Attribute) iterator.next();
                obj.put(attr.getName(), attr.getValue());
            }
            obj.put(list.get(0).getName(), iterateElement(list.get(0)));
        } else {
            List<Map<String, Object>> sons = new LinkedList<>();
            for (Element e : list) {
                sons.add(iterateElement(e));
            }
            obj.put(list.get(0).getName(), sons);
        }

        return obj;
    }
}
